#pragma once

#include <pthread.h>
#include <list>
#include <vector>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
#include <algorithm>    // std::find

using namespace std;

typedef void (*task_t)(void* arg);

typedef void* (*pool_task_t)(void* arg);

void* ThreadWorkFun(void* arg);

typedef struct 
{
    // 任务函数
    task_t do_task;
    // 任务传递参数
    void* arg;
    
}TaskNode,*PTaskNode;




#define MAX_THREAD      100
#define MAX_TASK        1000 
#define DEFAULT_THREAD  1


/**
 * @brief 线程池
 * 
 *        使用单例模式
 * 
 */
class Pool
{
private:
    // 互斥锁
    pthread_mutex_t Mutex;
    // 条件变量
    pthread_cond_t Cond;
    //　任务列表
    list<TaskNode>  TaskLists;
    //　线程向量
    vector<pthread_t> ThreadLists;

    //　当前任务数量
    unsigned int CurTask;
    // 活跃线程数量
    unsigned int ActiveTread;

    //最大的线程数量
    unsigned int MaxTask;
    unsigned int MaxThread;
    unsigned int MinThread;

    Pool(unsigned int active,unsigned int max_task,unsigned int max_thread,unsigned int min_thread);

    static Pool *PollInstance;
    static task_t   Task_fun;

public:
    
    // 禁止拷贝构造  赋值
    Pool(const Pool& other) = delete;
    void operator=(const Pool&) = delete;

    // 线程工作函数
    friend void* ThreadWorkFun(void* arg);

    static void* Thread_Fun(void* arg);

    // static Pool&  GetInstance(unsigned int active=DEFAULT_THREAD, unsigned int max_task=MAX_TASK,unsigned int max_thread=MAX_THREAD,unsigned int min_thread=1);
    static Pool*  GetInstance(unsigned int active=DEFAULT_THREAD, unsigned int max_task=MAX_TASK,unsigned int max_thread=MAX_THREAD,unsigned int min_thread=1);
    ~Pool();


    bool Set_TaskFun(task_t taskfun);

    unsigned int Add_Thread(unsigned int num);
    unsigned int Del_Thread(unsigned int num);

    bool Add_Task(TaskNode& tasknode);
    bool Add_Task(int fd);

    bool Del_Task(int fd);
    bool Del_Task(const TaskNode& tasknode);
    unsigned int Del_Task(unsigned int num);



    unsigned int Get_Active(void) const;
    unsigned int Get_TaskCount(void) const;
    unsigned int Get_MaxTask(void) const;
    unsigned int Get_MaxThread(void) const;
    unsigned int Get_MinThread(void) const;
    
    void Set_MaxTask(unsigned int num);
    void Set_MaxThread(unsigned int num);
    void Set_MinThread(unsigned int num);

};


